<template>
	<view class="container" v-if="loading">
		<view class="indexLogin">
			<view>正在登录，请稍候...</view>
		</view>
		<view class="goback" style="background: #f7f7f7;  color: #e4e7ed; border: none;">首页</view>
	</view>
</template>
<script>
	export default {
		components: {},
		data() {
			return {
				loading: false,
				myPageData:null,
				successUrl: '',
				nowStamp: (new Date()).getMilliseconds(),
				url: getApp().globalData.url,
				queryExpireApi:"/wxlogin/hasout", 			//TODO 是否登录掉线
				queryAuthUrlApi:"/wxlogin/wxauthurl",  		//TODO 获取授权URL地址
				queryTokenExpireApi:"/wxlogin/expireToken", //TODO 是否TOKEN过期方案
				loginAuthParam:false, 						//TODO授权所需参数对象
				currentStep:undefined,
				loginAuthToken:undefined
			};
		}, 
		onShow() {
			console.log("【页面显示】onShow ");
			let isWechatAuth = false; //1、首先判断是否微信内的浏览器
			console.log("【页面显示】加载 isWechatAuth",isWechatAuth);
		},
		onLoad(options) {
			let myHost = window.location;
			let DevInfo = this.$api.getSourceDevice();
			console.log("【公共入口】 设备信息=>",DevInfo);
			//TODO 获取传入的参数内容
			let myParam  = this.parseRequestQuery(); 
			this.myPageData = myParam;
			this.currentStep = uni.getStorageSync("STEPINDEX");
			console.log("【公共入口】 传入页面参数 StepIndex=>"+this.currentStep,this.myPageData);
			//this.$api.msg(JSON.stringify(DevInfo));
			//TODO 设备信息【H5类型，不管是不是手机都跳到其它页面】
			if(null !==DevInfo.platform && DevInfo.platform=="wechatMP" && DevInfo.isWechat===true){
				let loginToken = uni.getStorageSync('ENV_SUCCESSTOKEN') ? uni.getStorageSync('ENV_SUCCESSTOKEN') : '';
				this.loginAuthToken = loginToken?loginToken:undefined;
				this.onLoadPageFunc();  //TODO 启动当前页面业务【登录验证】
			}else{
				console.log("【公共入口】重定向【临时二维码页面】");
				this.navurl('/pages/qrcode/index',3); //TOD永久跳转
			}
			console.log("【公共入口】加载完成");
		},
		methods: {
			onLoadPageFunc() {
				let _that = this ; 
				uni.removeStorageSync("STEPINDEX");
				uni.removeStorageSync("AUTH_JUMPURL");		//TODO 请求授权跳转H5地址
				uni.removeStorageSync("AuthJumpLoginUser");	//TODO 授权没过期的数据
				//localStorage.removeItem("authLoginParam");//TODO 请求授权地址用的数据
				//localStorage.removeItem("jumpLoginData");	
				console.log("【LoadPageFunc-加载】 检测本地是否存用户TOKEN数据=>" + this.loginAuthToken);
				//TODO 是否有TOKEN,有就要先去验证TOKEN是否成功
				if(undefined !== this.loginAuthToken && null !== this.loginAuthToken && "" !== this.loginAuthToken){
					//TODO 本地模式跳转
					console.log("【LoadPageFunc-加载】 本地TOKEN验证， =>【TOKEN验证跳转】");
					_that.queryUserTokenExpire(); 
				}else{
					//TODO 正常跳转
					console.log("【LoadPageFunc-加载】 本地无TOKEN => 直接进【授权模式跳转】");
					_that.queryUserAuthExpire(); 
				}
			},
			//TODO  检测会员【TOKEN是否过期】；
			async queryUserTokenExpire() {
				let _that = this;
				uni.setStorageSync("STEPINDEX",0);
				let domainId = this.myPageData.dx || 0;
				//3、验证TOKEN是否过期，验证登录[同时也验证是否Session过期]
				this.$api.request({
					url: this.url + this.queryTokenExpireApi,
					method: 'POST',
					data: {token:this.loginAuthToken,"dx": domainId },
					success: res => {
						let resData = res.data || null;
						console.log("【queryUserTokenExpire】请求结果返回" ,resData);
						if (res.code == 200) {
							this.loading = true ;
							let validAuth = resData.validAuth || 0;	//TODO 是否在线【跳微信授权】
							let hasJumpUrl = resData.jumpUrl || "";
							let jumpH5Url = resData.h5PageUrl || "";
							let onlineToken = resData.userToken || "";
							
							//TODO 登录身份还在线，就直接返回登录成功的地址（如果没通过就返回授权完整地址:直接授权跳出去）
							if(null !==validAuth && validAuth==1 && hasJumpUrl && null !== onlineToken && "" !== onlineToken){
								
								this.loginAuthParam = false;
								uni.setStorageSync("STEPINDEX",3);//TODO 需要授权登录
								//TODO 身份没过期，就直接通过这个H5链接地址跳出去
								uni.setStorageSync('AuthJumpLoginUser', resData); //TODO 存在数据对象
								uni.setStorageSync('ENV_SUCCESSTOKEN', onlineToken);
								console.log("【queryUserTokenExpire】跳转jump成功",hasJumpUrl);
								this.successUrl=hasJumpUrl;
								this.jumpPage(hasJumpUrl); //TODO 正常跳转到H5成功页面
							}else{
								//TODO 验证不通过，就直接返回【授权地址】
								uni.setStorageSync("STEPINDEX",2);
								if(null !== jumpH5Url && undefined !== jumpH5Url && ""!==jumpH5Url){
									//TODO页面跳转
									uni.setStorageSync("AUTH_JUMPURL",jumpH5Url); 
									setTimeout(() => {
										//TODO 获取授权完整地址；
										//TODO 成功后就去进入微信授权页面
										_that.jumpPage(jumpH5Url); 
									},1000);
								}else{
									this.$api.msg("未知错误");
									return;
								}
							}
						} else {
							this.$api.msg(res.msg);
							return;
						}
					}
				}); 
				
				
			},
			
			//TODO  检测会员【授权是否过期】；
			async queryUserAuthExpire() {
				this.loading = true;
				let queryExpireApi=this.queryExpireApi;
				let mdString = this.myPageData.mdstr || "";
				let subParam = {"mdstr":mdString,"gIndex":this.myPageData.gIndex || 0};
				console.log("【queryUserAuthExpire】请求接口"+queryExpireApi,subParam);
				if(null===mdString || undefined===mdString|| ""===mdString) {
					uni.showToast({ title:"链接无效" ,duration:3000,"icon":'error',mask:true });
					return;
				}
				//3、本地没有就去服务器检测，并登录授权身份；
				this.$api.request({
					url: this.url + queryExpireApi,
					method: 'POST',
					data: subParam,
					success: res => {
						let resData = res.data || null;
						console.log("【queryUserAuthExpire】请求结果返回" ,resData);
						if (res.code == 200) {
							this.loading = true ;
							let validAuth = resData.validAuth || 0;	//TODO 是否在线【跳微信授权】
							let hasJumpUrl = resData.jumpUrl || "";
							let jumpH5Url = resData.h5PageUrl || "";
							let onlineToken = resData.userToken || "";
							//TODO 登录身份还在线
							if(null !==validAuth && validAuth==1 && hasJumpUrl && null !== onlineToken && "" !== onlineToken){
								this.loginAuthParam = false;
								//TODO 身份没过期，就直接通过这个H5链接地址跳出去
								uni.setStorageSync('AuthJumpLoginUser', resData); //TODO 存在数据对象
								uni.setStorageSync('ENV_SUCCESSTOKEN', onlineToken);
								console.log("【checkLocalStorageUser】跳转jump成功",hasJumpUrl);
								this.successUrl=hasJumpUrl;
								this.jumpPage(hasJumpUrl); //TODO 正常跳转到H5成功页面
							}else{
								this.loginAuthParam = {
									"hasAuth":0,
									"authUrl":resData.authUrl,
									"h5PageUrl":resData.h5PageUrl,
									"state":resData.authState ,
								};
								uni.setStorageSync("STEPINDEX",1);//TODO 需要授权登录
								if(null !== jumpH5Url && undefined !== jumpH5Url && ""!==jumpH5Url){
									//TODO页面跳转
									uni.setStorageSync("AUTH_JUMPURL",jumpH5Url); 
								}
								//TODO 获取授权完整地址；成功后就去进入微信授权页面
								//TODO 授权信息直接传到下一个接口处理
								this.findWxAuthService(this.loginAuthParam);  
							}
						} else {
							this.$api.msg(res.msg);
							return;
						}
					}
				}); 
			},
			//3、获取授权接口
			async findWxAuthService(subParam) {
				let queryAuthApi=this.queryAuthUrlApi;
				if(!subParam){
					subParam =  this.loginAuthParam;
				}
				//uni.showToast({ title:"授权处理中..." });
				console.log("【findWxAuthService】获取参数loginAuthParam=>",subParam);
				this.$api.request({
					url: this.url + queryAuthApi,
					method: 'POST',
					data: subParam,
					success: res => {
						let resData = res.data || null;
						console.log("【findWxAuthService】请求接口"+queryAuthApi,resData);
						if (res.code == 200) {
							let authJumpUrl = resData.requestUrl || "";
							if(null !== authJumpUrl && ""!==authJumpUrl){
								uni.setStorageSync("STEPINDEX",2);
								//TODO 跳转授权页面；
								console.log("【findWxAuthService】跳转授权地址 => ",authJumpUrl);
								this.jumpPage(authJumpUrl); 
							}else{
								this.$api.msg("获取数据错误，请重试");
							}
							return;
						} else {
							this.$api.msg(res.msg);
							return;
						}
					}
				}); 
			},
			//TODO 检测授权是否过期，
			checkLocalStorageUser(){
				let jumpLoginData = uni.getStorageSync("AuthJumpLoginUser"); //TODO 本地储存的数据
				let loginAuth = jumpLoginData?jumpLoginData:null;
				console.log("【checkLocalStorageUser】本地缓存跳转jump数据",loginAuth);
				let jumpSucUrl = loginAuth && loginAuth.jumpUrl || '';
				let jumpExpire = loginAuth && loginAuth.expire || 0;
				if(null !== loginAuth && jumpExpire > this.nowStamp && null !== jumpSucUrl && "" !== jumpSucUrl){
					//TODO 没过期，直接跳到H5页面去；
					console.log("【checkLocalStorageUser】跳转jump成功",jumpSucUrl);
					this.jumpPage(jumpSucUrl); 
				}
			},
			//TODO 请求参数解析值
			parseRequestQuery() {
				const search = new URLSearchParams(window.location.search);
				const res = {};
				search.forEach((value, key) => {
					let arr = res[key];
					if (arr === undefined) {
						arr = res[key] = value;
					} else if (Array.isArray(arr)) {
						arr.push(value);
					} else {
						res[key] = [arr, value];
					}
				});
				return res;
			},
			//TODO 跳转出去页面
			jumpPage(url){
				console.log("【jumpPage】跳转出去",url);
				//TODO 重定向出去
				//window.location.href = url; 
				return ;
			}
		}
	};
</script>

<style lang="scss">
	page,.container{
		background: #fff;
		width: 100%;
		min-height: 100%; 
		text-align: center;
		position: relative;
	}
	.bg{
		width: 700upx;
		margin: 20upx auto;
		height: 1304upx;
	}
	.indexLogin {
		background: #e5e5e5;
		min-height: 900px;
		padding: 100px;
		color: #888;
		font-size: 18px;
	}
</style>